package com.tjetc;

import com.tjetc.utils.JdbcUtil;
import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @ author: gaoyongxiang
 * @ date: 2025/8/15
 * @ version: v1.0
 */
public class _5Transaction {
    // 不使用事务
    @Test
    public void testTransfer1(){
        PreparedStatement preparedStatement = null;
        Connection connection = null;
        try {
            connection = JdbcUtil.getConnection();

            String subMoney = "update bank set money = money - 500 where name = 'zhangsan';";
            String addMoney = "update bank set money = money + 500 where name = 'lisi';";

            preparedStatement = connection.prepareStatement(subMoney);
            preparedStatement.executeUpdate();
            int a = 1 / 0;
            preparedStatement = connection.prepareStatement(addMoney);
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        } finally {
            JdbcUtil.close(null, preparedStatement, connection);
        }
    }



    // 使用事务
    @Test
    public void testTransfer2(){
        PreparedStatement preparedStatement = null;
        Connection connection = null;
        try {
            connection = JdbcUtil.getConnection();
            // 取消自动提交
            connection.setAutoCommit(false);
            String subMoney = "update bank set money = money - 500 where name = 'zhangsan';";
            String addMoney = "update bank set money = money + 500 where name = 'lisi';";

            preparedStatement = connection.prepareStatement(subMoney);
            preparedStatement.executeUpdate();
            int a = 1 / 0;
            preparedStatement = connection.prepareStatement(addMoney);
            preparedStatement.executeUpdate();

            // 如果执行完毕则需要手动提交事务
            connection.commit();
        } catch (SQLException e) {
            try {
                // 执行回滚的语句
                connection.rollback();
            } catch (SQLException ex) {
                System.out.println(e.getMessage());
            }
            System.out.println(e.getMessage());
        } finally {
            JdbcUtil.close(null, preparedStatement, connection);
        }

    }
}